package org.social.manager;

import java.util.ArrayList;
import java.util.List;

import org.bean.DictionariesDTO;
import org.constant.ActionEnum;
import org.constant.ServerTypeEnum;
import org.social.db.bean.Dictionaries;
import org.social.db.cache.DictionariesCache;
import org.utils.RemoteUtil;

import com.google.common.collect.Lists;
import com.xiaoleilu.hutool.bean.BeanUtil;

/**
 * @author : DengYing
 * @CreateDate : 2018年2月8日 下午3:46:03
 * @Description ：字典库管理器
 */
public class DictionariesManager {
	
	public static void notifyRemote(ServerTypeEnum type,String serverId) {
		List<Dictionaries> list = DictionariesCache.me().loadAll();
		List<DictionariesDTO> notifyList = new ArrayList<>(list.size());
		DictionariesDTO dto = null;
		for (Dictionaries dictionaries : list) {
			dto = buildDictionariesDTO(dictionaries,ActionEnum.DEFAULT);
			notifyList.add(dto);
		}
		
//		if (!notifyList.isEmpty()) {
			switch (type) {
			case GAME_SERVER:
				RemoteUtil.gameAsyn(serverId).noticeDict(notifyList);
				break;
			default:
				break;
			}
//		}
	}
	
	
	/** 添加文字
	 * @return */
    public static void putEntry(String language,String contentKey, String contentVal) {
        List<DictionariesDTO> noticeList = Lists.newArrayList();
    	Dictionaries dict = DictionariesCache.me().getByLanguageContentKey(language, contentKey);
    	
    	ActionEnum action = null;
    	if (dict!=null) {
    		dict.setContentVal(contentVal);
    		dict.update();
    		action = ActionEnum.UPDATE;
		}else {
			dict = new Dictionaries(0, language, contentKey, contentVal);
			dict.insert();
			action = ActionEnum.ADD;
		}
    	
    	noticeList.add(buildDictionariesDTO(dict, action));
    	RemoteUtil.gameTopic().noticeDict(noticeList);
    }
    
    /** 删除文字 */
    public static void remove(List<Integer> ids) {
    	List<DictionariesDTO> noticeList = new ArrayList<>(ids.size());
    	for (int id : ids) {
    		Dictionaries dict = DictionariesCache.me().getById(id);
    		if (dict == null) {
				continue;
			}
    		dict.delete();
    		noticeList.add(buildDictionariesDTO(dict, ActionEnum.REMOVE));
		}
    	// 通知
    	RemoteUtil.gameTopic().noticeDict(noticeList);
    }

	private static DictionariesDTO buildDictionariesDTO(Dictionaries dictionaries, ActionEnum action) {
		DictionariesDTO dto = new DictionariesDTO();
		BeanUtil.copyProperties(dictionaries, dto);
		dto.setAction(action);
		return dto;
	}
}
